package com.shujia.kafka

import java.util.Properties

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}

object Demo4Trans {

  def main(args: Array[String]): Unit = {

    val properties = new Properties()

    //指定kafka的broker的地址
    properties.setProperty("bootstrap.servers", "master:9092")
    //key和value序列化类
    properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    properties.setProperty("transactional.id", "asdasdasdasd")


    //生产者
    val producer = new KafkaProducer[String, String](properties)

    //初始化事务
    producer.initTransactions()
    //开启事务
    producer.beginTransaction()



    //在send的时候数据实际上已经发送到kafka中，单词数据在kafka中是一个未提交的状态
    producer.send(new ProducerRecord[String, String]("trans", "java"))

    Thread.sleep(5000)

    producer.send(new ProducerRecord[String, String]("trans", "spark"))

    //提交事务
    producer.commitTransaction()

    producer.close()

    /**
      * --isolation-level read_committed   读已提交数据
      * kafka-console-consumer.sh --bootstrap-server  master:9092 --isolation-level read_committed  --from-beginning --topic trans
      *
      */


  }

}
